package com.thinkit.bigdata.core.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA加密工具类
 * Created by lihongli on 2019/4/2
 */
public class RSAUtil {
    private static Logger logger = LoggerFactory.getLogger(RSAUtil.class);

    private RSAUtil(){}

    public static final String PRIVATE_KEY = "privateKey";

    public static Map<Integer, String> genKeyPair() {
        Map<Integer, String> keyMap = new HashMap<>();
        try {
            // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥对生成器，密钥大小为96-1024位
            keyPairGenerator.initialize(512, new SecureRandom());
            // 生成一个密钥对，保存在keyPair中
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());
            String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
            keyMap.put(0, publicKeyStr);
            keyMap.put(1, privateKeyStr);
        } catch (NoSuchAlgorithmException e) {
            logger.error("生成RSA密匙对过程中出错", e);
        }
        return keyMap;
    }

    /**
     * RSA私匙加密
     *
     * @param str        要解密的字符串
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String str, String privateKey) {
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            logger.error("解密过程中出错", e);
            return null;
        }
    }
}
